<!-- eslint-disable no-console -->
<script setup>
import { onMounted, ref } from 'vue'
import G6 from '@antv/g6'

// 定义事件，和父组件html中保持一致
const emit = defineEmits(['stepNodeClicked'])

const data = {
  nodes: [
    {
      id: '原始病例',
      label: '原始病例',
    },
    {
      id: '预处理',
      label: '预处理',
    },
    {
      id: '血压分级',
      label: '血压分级',
    },
    {
      id: '危险分层',
      label: '危险分层',
    },
  ],
  edges: [
    {
      source: '原始病例',
      target: '预处理',
    },
    {
      source: '预处理',
      target: '血压分级',
    },
    {
      source: '血压分级',
      target: '危险分层',
    },
  ],
}

const flowchartContainer = ref(null)
const graph = ref(null)

onMounted(() => {
  if (flowchartContainer.value) {
    console.log(flowchartContainer)
    graph.value = new G6.Graph({
      container: flowchartContainer.value,
      width: flowchartContainer.value.offsetWidth,
      height: flowchartContainer.value.offsetHeight,
      fitView: true,
      modes: {
        default: ['drag-canvas', 'drag-node'],
      },
      layout: {
        type: 'dagre',
        rankdir: 'LR',
        align: 'UL',
        controlPoints: true,
        nodesepFunc: () => 1,
        ranksepFunc: () => 1,
      },
      defaultNode: {
        size: [50, 20],
        type: 'rect',
        style: {
          lineWidth: 2,
          stroke: '#5B8FF9',
          fill: '#C6E5FF',
        },
      },
      defaultEdge: {
        type: 'polyline',
        size: 2,
        color: '#e2e2e2',
        style: {
          endArrow: {
            path: 'M 0,0 L 8,4 L 8,-4 Z',
            fill: '#e2e2e2',
          },
          radius: 20,
        },
      },
    })

    graph.value.data(data)
    graph.value.render()
  }
  // TODO: 点击节点触发的结果需要和后端传回数据对齐
  graph.value.on('node:click', (evt) => {
    const nodeModel = evt.item.getModel()
    // 使用emit扔给父组件
    emit('stepNodeClicked', { stepName: nodeModel.label })
    console.log(nodeModel.label)
  })
})
</script>

<template>
  <div ref="flowchartContainer" class="g6" />
</template>

<style scoped>
.g6 {
  width: 100%;
  height: 100%;
  display: block;
  border: none;
  padding: none;
  box-sizing: border-box;
  background-color: 'white';
}
.highlight {
    font-weight: bold;
    background-color: rgb(44, 131, 48);
}
</style>
